package com.winshare.saleAssistant.service.impl;

import com.winshare.saleAssistant.constant.ReadStatus;
import com.winshare.saleAssistant.dao.FeedbackMapper;
import com.winshare.saleAssistant.domain.entity.FeedbackDO;
import com.winshare.saleAssistant.domain.query.FeedbackQuery;
import com.winshare.saleAssistant.domain.dto.req.FeedbackCreateDTO;
import com.winshare.saleAssistant.domain.dto.req.FeedbackIdDTO;
import com.winshare.saleAssistant.domain.dto.req.FeedbackQueryDTO;
import com.winshare.saleAssistant.domain.dto.req.FeedbackReplyDTO;
import com.winshare.saleAssistant.domain.dto.resp.FeedbackRespDTO;
import com.winshare.saleAssistant.mapper.FeedbackMapStruct;
import com.winshare.saleAssistant.service.FeedbackService;
import com.winshare.saleAssistant.util.Page;
import com.winshare.saleAssistant.util.RequestHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class FeedbackServiceImpl implements FeedbackService {

    private final FeedbackMapper feedbackMapper;

    public FeedbackServiceImpl(FeedbackMapper feedbackMapper) {
        this.feedbackMapper = feedbackMapper;
    }

    @Override
    public void save(FeedbackCreateDTO feedbackCreateDTO) {
        FeedbackDO feedbackDO = FeedbackMapStruct.INSTANCE.fromFeedbackCreateDTO(feedbackCreateDTO);
        feedbackDO.setCreator(RequestHolder.getCurrentUser().getStaffName());
        feedbackDO.setCreateTime(LocalDateTime.now().toString());
        feedbackMapper.saveFeedback(feedbackDO);
    }

    @Override
    public void setRead(FeedbackIdDTO feedbackIdDTO) {
        FeedbackDO feedbackDO = FeedbackMapStruct.INSTANCE.fromFeedbackIdDTO(feedbackIdDTO);
        feedbackDO.setStatus(ReadStatus.read);
        feedbackMapper.updateFeedback(feedbackDO);
    }

    @Override
    public void reply(FeedbackReplyDTO feedbackReplyDTO) {
        FeedbackDO feedbackDO = FeedbackMapStruct.INSTANCE.fromFeedbackReplyDTO(feedbackReplyDTO);
        feedbackMapper.updateFeedback(feedbackDO);
    }

    @Override
    public Page<FeedbackRespDTO> getFeedBackList(FeedbackQueryDTO feedbackQueryDTO) {
        FeedbackQuery feedbackQuery = FeedbackMapStruct.INSTANCE.fromFeedbackQueryDTO(feedbackQueryDTO);
        feedbackQuery.setOffsetIndex(feedbackQueryDTO.getOffsetIndex());
        int totalCount = feedbackMapper.queryFeedbackCount(feedbackQuery);
        Integer pageIndex = feedbackQueryDTO.getPageIndex();
        Integer pageSize = feedbackQueryDTO.getPageSize();
        if(0 == totalCount) {
            return new Page<>(pageIndex,pageSize,totalCount,new ArrayList<>());
        }
        List<FeedbackDO>  feedbackDOList = feedbackMapper.findFeedbackListByConditions(feedbackQuery);
        List<FeedbackRespDTO> feedbackRespDTOList = FeedbackMapStruct.INSTANCE.fromFeedbackDOList(feedbackDOList);
        return new Page<>(pageIndex,pageSize,totalCount,feedbackRespDTOList);
    }


}
